package models

import (
	"errors"
	"fmt"
	"strings"
	"time"

	"github.com/astaxie/beego/orm"
)

type TPatch struct {
	Id            int64     `orm:"column(id);auto" description:""  form:"id"  json:"id"`
	TAppId        int       `orm:"column(t_app_id)" description:"所属app 的id"  form:"t_app_id"  json:"t_app_id"`
	BundleID      string    `orm:"column(bundle_id)" description:"所属app 的BundleID"  form:"bundle_id"  json:"bundle_id"`
	Sn            string    `orm:"column(sn);size(45);null" description:"patch 的id"  form:"sn"  json:"sn"`
	Url           string    `orm:"column(url);size(105);null" description:"patch的下载地址"  form:"url"  json:"url"`
	Md5           string    `orm:"column(md5);size(65);null" description:"patch的md5"  form:"md5"  json:"md5"`
	Desc          string    `orm:"column(desc);null" description:"patch描述"  form:"desc"  json:"desc"`
	PreSn         string    `orm:"column(pre_sn);size(45);null" description:"当前patch id 的前置id，"  form:"pre_sn"  json:"pre_sn"`
	Createtime    time.Time `orm:"column(createtime);type(datetime);null" description:""  form:"createtime"  json:"createtime"`
	PatchOrSchema int8      `orm:"column(patch_or_schema);null" description:"本补丁是patch 还是schema"  form:"patch_or_schema"  json:"patch_or_schema"`
	Enable        int8      `orm:"column(enable);null" description:"1 为可用，0 为删除。默认为1"  form:"enable"  json:"enable"`
	Size          int       `orm:"column(size);null" description:"补丁的大小.单位byte"  form:"size"  json:"size"`
}

func (t *TPatch) TableName() string {
	return "t_patch"
}
func (t *TPatch) TableComment() string {
	return ""
}

func init() {
	orm.RegisterModel(new(TPatch))
}

// AddTPatch insert a new TPatch into database and returns
// last inserted Id on success.
func AddTPatch(m *TPatch) (id int64, err error) {
	o := orm.NewOrm()
	id, err = o.Insert(m)
	return
}

// GetTPatchById retrieves TPatch by Id. Returns error if
// Id doesn't exist
func GetTPatchById(id int64) (v *TPatch, err error) {
	o := orm.NewOrm()
	v = &TPatch{Id: id}
	if err = o.Read(v); err == nil {
		return v, nil
	}
	return nil, err
}

// GetAllTPatch retrieves all TPatch matches certain condition. Returns empty list if
// no records exist
func GetAllTPatch(query map[string]interface{}, fields []string, sortby []string, order []string,
	offset int64, limit int64, needCount bool) (ml []TPatch, totalCount int64, err error) {
	o := orm.NewOrm()
	qs := o.QueryTable(new(TPatch))
	// query k=v
	for k, v := range query {
		// rewrite dot-notation to Object__Attribute
		k = strings.Replace(k, ".", "__", -1)
		qs = qs.Filter(k, v)
	}
	// order by:
	var sortFields []string
	if len(sortby) != 0 {
		if len(sortby) == len(order) {
			// 1) for each sort field, there is an associated order
			for i, v := range sortby {
				orderby := ""
				if order[i] == "desc" {
					orderby = "-" + v
				} else if order[i] == "asc" {
					orderby = v
				} else {
					return nil, 0, errors.New("Error: Invalid order. Must be either [asc|desc]")
				}
				sortFields = append(sortFields, orderby)
			}
			qs = qs.OrderBy(sortFields...)
		} else if len(sortby) != len(order) && len(order) == 1 {
			// 2) there is exactly one order, all the sorted fields will be sorted by this order
			for _, v := range sortby {
				orderby := ""
				if order[0] == "desc" {
					orderby = "-" + v
				} else if order[0] == "asc" {
					orderby = v
				} else {
					return nil, 0, errors.New("Error: Invalid order. Must be either [asc|desc]")
				}
				sortFields = append(sortFields, orderby)
			}
		} else if len(sortby) != len(order) && len(order) != 1 {
			return nil, 0, errors.New("Error: 'sortby', 'order' sizes mismatch or 'order' size is not 1")
		}
	} else {
		if len(order) != 0 {
			return nil, 0, errors.New("Error: unused 'order' fields")
		}
	}

	var l []TPatch
	qs = qs.OrderBy(sortFields...)
	if needCount == true {
		if totalCount, err = qs.Count(); err != nil {

			return nil, 0, err
		}
	}
	if _, err = qs.Limit(limit, offset).All(&l); err == nil {

		return l, totalCount, nil
	}
	return nil, totalCount, err
}

// UpdateTPatch updates TPatch by Id and returns error if
// the record to be updated doesn't exist
func UpdateTPatchById(m *TPatch) (vo *TPatch, err error) {
	o := orm.NewOrm()
	v := TPatch{Id: m.Id}
	// ascertain id exists in the database
	//if err = o.Read(&v); err == nil {
	//var num int64
	if _, err = o.Update(m); err == nil {
		return m, nil
		//	fmt.Println("Number of records updated in database:", num)
	}
	//}
	return &v, nil
}

// DeleteTPatch deletes TPatch by Id and returns error if
// the record to be deleted doesn't exist
func DeleteTPatch(id int64) (err error) {
	o := orm.NewOrm()
	v := TPatch{Id: id}
	// ascertain id exists in the database
	if err = o.Read(&v); err == nil {
		var num int64
		if num, err = o.Delete(&TPatch{Id: id}); err == nil {
			fmt.Println("Number of records deleted in database:", num)
		}
	}
	return
}
